<?php

namespace App\Http\Middleware;

use App\Models\V1\Admins;
use Carbon\Carbon;
use Closure;
use Illuminate\Http\Request;

class AuthAdmin
{
    protected $timeError = 120;

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next,$role=null)
    {
        $res = $request->all();
        try {
            if($res['s'] !='//v1/admin/upload_users'){
                //必须是在时间范围内，并且签名校验成功
                if(($this->allowTimestamp($request) && $this->checkSign($request->header('timestamp'),$request->header('sign')))){
                    //二次验证权限
                    $user_id =auth('box_admin')->user()->id;
                    $admin_model = new Admins();
                    $param=getControllerAndActionName();

//                $bool = $admin_model->checkPermission($user_id,"*",$param['controller']."@".$param['method']);
//                if(!$bool){
//                    return ajax_output(300,"没有权限");
//                }
                    return $next($request);
                }else{
                    return ajax_output(300,"请求错误,非法请求");
                }
            }else{
                return $next($request);
            }


        } catch (\Exception $e) {
            return ajax_output(301,"token校验失败".$e->getMessage());
        }
        //todo 判断权限

        return $next($request);
    }

    /**
     * 判断用户请求是否在对应时间范围
     *
     * @author tubage
     * @param \Illuminate\Http\Request $request
     * @return boolean
     */
    protected function allowTimestamp($request)
    {
        $queryTime = Carbon::createFromTimestamp($request->header('timestamp', 0));
        $lfTime = Carbon::now()->subSeconds($this->timeError);
        $rfTime = Carbon::now()->addSeconds($this->timeError);
        if ($queryTime->between($lfTime, $rfTime, true)) {
            return true;
        }
        return false;
    }

    /**
     * 验证签名
     * @param $data
     * @param $sign
     * @return bool
     */
    protected function checkSign($timestamp="",$sign=""){
        if(strtoupper(md5("SC.".$timestamp.".SC"))==$sign){
            return true;
        }
        return false;
    }
}
